package cn.candy.basic.controller;

import cn.candy.basic.util.AjaxResult;
import cn.candy.basic.util.FastDfsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 上传
 * 下载 = 不需要
 * 查看 = 路径: http://47.95.117.210:8888/group1/M00/01/ED/rBE3kWGtvoGAN8VNAAAWm-sTx0A067.jpg
 * 删除
 * 更新 = 删除 + 上传
 * 文件上传接口
 */
@Api(tags = "FastDfs文件处理接口",description = "文件上传+文件删除")
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    //MultipartFile对象需要用 @RequestPart接收
    //value = "file" - 与ElementUi提供的组件中name="file"一致

    /**
     * 文件上传接口
     * @param file - 复杂表单数据
     * @return - 只关注成功与否
     */
    @ApiOperation(value = "文件上传接口",notes = "")
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file){
        try {
            System.out.println(file.getOriginalFilename() + ":" + file.getSize());
            String originalFilename = file.getOriginalFilename();
            // xxx.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            //工具类返回的完整路径：/goup1/xxxxx/yyyy
            String filePath =  FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath); //把上传后的路径返回回去
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("上传失败!"+e.getMessage());
        }
    }
    /**
     * 文件删除接口
     * 参数：完整路径 /goup1/xxxxx/yyyy
     * 返回值：成功与否，还要返回地址
     */
    @ApiOperation(value = "文件删除接口",notes = "")
    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        try {
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
            FastDfsUtil.delete(groupName, remotePath);
            return  AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("删除失败!"+e.getMessage());
        }
    }
}